package com.demo.accessibilitykeeper;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

/**
 * 系统事件广播接收器
 * 监听系统关机、重启等事件
 */
public class SystemReceiver extends BroadcastReceiver {
    
    private static final String TAG = "SystemReceiver";
    private static final String PREFS_NAME = "accessibility_keeper_prefs";
    private static final String KEY_LAST_SHUTDOWN_TIME = "last_shutdown_time";
    private static final String KEY_SHUTDOWN_COUNT = "shutdown_count";
    
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(TAG, "SystemReceiver onReceive, action: " + action);
        
        if (action == null) {
            return;
        }
        
        switch (action) {
            case Intent.ACTION_SHUTDOWN:
                handleShutdown(context);
                break;
            case Intent.ACTION_REBOOT:
                handleReboot(context);
                break;
            default:
                Log.d(TAG, "Unhandled action: " + action);
                break;
        }
    }
    
    /**
     * 处理系统关机事件
     */
    private void handleShutdown(Context context) {
        Log.d(TAG, "Handling system shutdown");
        
        // 记录关机时间
        recordShutdownTime(context);
        
        // 保存服务状态
        saveServiceState(context);
        
        // 执行清理操作
        performCleanup(context);
    }
    
    /**
     * 处理系统重启事件
     */
    private void handleReboot(Context context) {
        Log.d(TAG, "Handling system reboot");
        
        // 记录重启时间
        recordRebootTime(context);
        
        // 保存服务状态
        saveServiceState(context);
        
        // 执行清理操作
        performCleanup(context);
    }
    
    /**
     * 记录关机时间
     */
    private void recordShutdownTime(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        long currentTime = System.currentTimeMillis();
        
        int shutdownCount = prefs.getInt(KEY_SHUTDOWN_COUNT, 0);
        
        prefs.edit()
            .putLong(KEY_LAST_SHUTDOWN_TIME, currentTime)
            .putInt(KEY_SHUTDOWN_COUNT, shutdownCount + 1)
            .apply();
        
        Log.d(TAG, "Shutdown time recorded: " + currentTime + ", count: " + (shutdownCount + 1));
    }
    
    /**
     * 记录重启时间
     */
    private void recordRebootTime(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        long currentTime = System.currentTimeMillis();
        
        prefs.edit()
            .putLong("last_reboot_time", currentTime)
            .apply();
        
        Log.d(TAG, "Reboot time recorded: " + currentTime);
    }
    
    /**
     * 保存服务状态
     */
    private void saveServiceState(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        
        // 保存当前服务状态
        prefs.edit()
            .putBoolean("service_was_running", true)
            .putLong("last_service_stop_time", System.currentTimeMillis())
            .apply();
        
        Log.d(TAG, "Service state saved");
    }
    
    /**
     * 执行清理操作
     */
    private void performCleanup(Context context) {
        Log.d(TAG, "Performing cleanup operations");
        
        try {
            // 停止所有服务
            stopAllServices(context);
            
            // 清理临时文件
            cleanupTempFiles(context);
            
            // 保存重要数据
            saveImportantData(context);
            
        } catch (Exception e) {
            Log.e(TAG, "Error during cleanup", e);
        }
    }
    
    /**
     * 停止所有服务
     */
    private void stopAllServices(Context context) {
        try {
            // 停止保活服务
            Intent keepAliveIntent = new Intent(context, KeepAliveService.class);
            context.stopService(keepAliveIntent);
            
            // 停止前台服务
            Intent foregroundIntent = new Intent(context, ForegroundService.class);
            context.stopService(foregroundIntent);
            
            Log.d(TAG, "All services stopped");
            
        } catch (Exception e) {
            Log.e(TAG, "Error stopping services", e);
        }
    }
    
    /**
     * 清理临时文件
     */
    private void cleanupTempFiles(Context context) {
        try {
            // 清理应用临时目录
            java.io.File tempDir = new java.io.File(context.getCacheDir(), "temp");
            if (tempDir.exists()) {
                deleteDirectory(tempDir);
            }
            
            Log.d(TAG, "Temp files cleaned up");
            
        } catch (Exception e) {
            Log.e(TAG, "Error cleaning up temp files", e);
        }
    }
    
    /**
     * 删除目录
     */
    private void deleteDirectory(java.io.File dir) {
        if (dir.isDirectory()) {
            java.io.File[] children = dir.listFiles();
            if (children != null) {
                for (java.io.File child : children) {
                    deleteDirectory(child);
                }
            }
        }
        dir.delete();
    }
    
    /**
     * 保存重要数据
     */
    private void saveImportantData(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        
        // 保存服务运行统计
        long totalRunTime = System.currentTimeMillis() - 
            prefs.getLong("service_start_time", System.currentTimeMillis());
        
        prefs.edit()
            .putLong("total_run_time", totalRunTime)
            .putLong("last_cleanup_time", System.currentTimeMillis())
            .apply();
        
        Log.d(TAG, "Important data saved, total run time: " + totalRunTime);
    }
    
    /**
     * 获取关机统计信息
     */
    public static ShutdownStats getShutdownStats(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        
        ShutdownStats stats = new ShutdownStats();
        stats.lastShutdownTime = prefs.getLong(KEY_LAST_SHUTDOWN_TIME, 0);
        stats.shutdownCount = prefs.getInt(KEY_SHUTDOWN_COUNT, 0);
        stats.lastRebootTime = prefs.getLong("last_reboot_time", 0);
        stats.totalRunTime = prefs.getLong("total_run_time", 0);
        
        return stats;
    }
    
    /**
     * 关机统计信息数据类
     */
    public static class ShutdownStats {
        public long lastShutdownTime;
        public int shutdownCount;
        public long lastRebootTime;
        public long totalRunTime;
    }
}
